package cn.parus.controller;

import cn.hutool.core.io.FileUtil;
import cn.parus.common.Execption.Result;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件相关操作接口
 */
@RestController
@RequestMapping("/files")
public class FileController {

    // 表示本地磁盘文件的存储路径
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Value("${fileBaseUrl}")
    private String fileBaseUrl;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        // 定义文件的唯一标识（时间戳+原始文件名）
        String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
        // 拼接完整的文件存储路径
        String realFilePath = filePath + fileName;
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            FileUtil.writeBytes(file.getBytes(), realFilePath);
        } catch (IOException e) {
            System.out.println("文件上传错误");
            return Result.error("文件上传失败");
        }

        // 构造返回的文件信息（包含所有重要字段）
        Map<String, Object> fileInfo = new HashMap<>();
        fileInfo.put("fileId", fileName);                  // 文件唯一标识（时间戳+原始名）
        fileInfo.put("originalFileName", file.getOriginalFilename());  // 原始文件名
        fileInfo.put("fileSize", file.getSize());           // 文件大小（字节）
        fileInfo.put("fileType", getFileType(file.getOriginalFilename())); // 文件类型（扩展名）
        fileInfo.put("downloadUrl", fileBaseUrl + "/files/download/" + fileName);  // 下载链接
        fileInfo.put("storagePath", realFilePath);          // 服务器存储路径

        return Result.success(fileInfo);
    }

    /**
     * 文件下载
     */
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) {
        // 设置下载文件http响应头
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        // 拼接完整的文件存储路径
        String realFilePath = filePath + fileName;
        try {
            // 通过文件的存储路径拿到文件字节数组
            byte[] bytes = FileUtil.readBytes(realFilePath);
            ServletOutputStream os = response.getOutputStream();
            // 将文件字节数组写出到文件流
            os.write(bytes);
            os.flush();
            os.close();
        } catch (IOException e) {
            System.out.println("文件下载错误");
        }
    }

    private static final String WEBHDFS_URL = "http://hadoop001:9864/webhdfs/v1/";
    private static final String NAMENODE_RPC_ADDRESS = "120.76.55.71:8020";

    @GetMapping("/download-from-hdfs/{fileId}/{fileName}")
    public void downloadFormHDFS(@PathVariable String fileId, @PathVariable String fileName, HttpServletResponse response) {
        String webhdfsRequestUrl = WEBHDFS_URL + fileId + "?op=OPEN" + "&namenoderpcaddress=" + NAMENODE_RPC_ADDRESS + "&offset=0";
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;

        try {
            // 打开WebHDFS连接
            URL url = new URL(webhdfsRequestUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 设置响应头
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
                response.setContentType("application/octet-stream");

                // 获取输入输出流
                inputStream = connection.getInputStream();
                outputStream = response.getOutputStream();

                // 复制文件内容
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
            } else {
                // 处理错误响应
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                System.out.println("WebHDFS请求失败，状态码: " + responseCode);
            }
        } catch (IOException e) {
            System.out.println("文件下载错误：" + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        } finally {
            // 确保资源关闭
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
                if (connection != null) connection.disconnect();
            } catch (IOException e) {
                System.out.println("关闭资源错误：" + e.getMessage());
            }
        }
    }

    // 辅助方法：从文件名中提取扩展名（如 "record.md" -> "md"）
    private String getFileType(String fileName) {
        int dotIndex = fileName.lastIndexOf(".");
        return dotIndex > 0 ? fileName.substring(dotIndex + 1) : "unknown";
    }
}
